//
//  OpinionViewController.swift
//  BellManage
//
//  Created by Bestsch on 16/4/1.
//  Copyright © 2016年 wsl. All rights reserved.
//

import UIKit

class OpinionViewController: BaseViewController,UICollectionViewDelegate,UICollectionViewDataSource,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,MBProgressHUDDelegate,AJPhotoPickerProtocol,UITextViewDelegate,AJPhotoBrowserDelegate {
    
    
    var contentField: UITextView!
    var placeholderLabel: UILabel!
    
    var photoCollectionView: UICollectionView!
    
    var photoArray = NSMutableArray()
    
    let collectionIdentifier = "PhotoCollectionViewCellIdentifier"
    
    
    var hud: MBProgressHUD!
    var baseStr: String!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "提交", style: UIBarButtonItemStyle.done, target: self, action: #selector(OpinionViewController.send))
        self.title = "意见反馈"
        self.automaticallyAdjustsScrollViewInsets = false

        InitViews()
        
    }
    
    func send() {
        hud = MBProgressHUD.showAdded(to: self.view, animated: true)
        hud.mode = MBProgressHUDMode.indeterminate
        hud.labelText = "正在提交反馈...请稍后"
        
        let queue = DispatchQueue(label: "queue")
        queue.async {
            //            sleep(3)
            /**
             *  "<?xml version=\"1.0\" encoding=\"utf-8\"?><rss version=\"2.0\"><t>4</t><ftype>%@</ftype><classid>%@</classid><schid>%@</schid><fcontent>%@</fcontent><fimg>%@</fimg><fIP>%@</fIP><fperson>%@</fperson><mobileName>%@</mobileName><farea>%@</farea><tel>%@</tel></rss>"
             *
             *  @param dispatch_get_main_queue <#dispatch_get_main_queue description#>
             *
             *  @return <#return value description#>
             */
            let user = getUserPojo()
            var ims = ""
            if self.photoArray.count != 0 {
                for i in 0...self.photoArray.count - 1 {
                    
                    var image: UIImage!
                    if (self.photoArray.object(at: i) as AnyObject).isKind(of: UIImage.superclass()!){
                        image = self.photoArray.object(at: i) as! UIImage
                    }else{
                        let asset: ALAsset = self.photoArray.object(at: i) as! ALAsset
                        image = UIImage.init(cgImage: asset.defaultRepresentation().fullResolutionImage().takeUnretainedValue())
                    }
                    let picData = UIImageJPEGRepresentation(image, 0.1)
                    print("图片大小\((picData?.count)!/1024)Kb")
                    let picStr: String = (picData?.base64EncodedString(options: NSData.Base64EncodingOptions.lineLength64Characters))!
                    if (i==0) {
                        ims = picStr;
                    }else{
                        ims = "\(ims)|\(picStr)"
                    }
                    
                }
            }
            let infoDictionary: NSDictionary = Bundle.main.infoDictionary! as NSDictionary
            let OperSysxml = UIDevice.current.systemVersion
            print("操作系统:\(OperSysxml)")
            let verNum = "系统：iOS\(OperSysxml),版本:\(infoDictionary.object(forKey: "CFBundleShortVersionString") as! String)"
            
            let request = "<?xml version=\"1.0\" encoding=\"utf-8\"?><rss version=\"2.0\"><t>4</t><ftype>1</ftype><classid></classid><schid>\(user.schid)</schid><fcontent>\(self.contentField.text!)</fcontent><fimg>\(ims)</fimg><fIP></fIP><fperson>\(user.userid)</fperson><mobileName>\(getPhoneMode()!)</mobileName><farea></farea><tel>\(user.userphone)</tel><VersionNum>\(verNum)</VersionNum></rss>"
            let url = server + "/webapp/apps/FeedBackHandler.ashx"
          
            let result = HttpUtils.httpPostUTF(url, with: request)
            
            DispatchQueue.main.async(execute: {
                self.hud.hide(true)
                
                if result == "True" {
                    TSMessage.showNotification(in: self, title: "提示", subtitle: "提交反馈成功，感谢您的宝贵建议，我们会更加完善产品！", image: nil, type: TSMessageNotificationType.success, duration: 2.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: true)
                    let index = self.navigationController?.viewControllers.index(of: self)
                    self.navigationController?.popToViewController((self.navigationController?.viewControllers[index! - 1])!, animated: true)
                    self.dismiss(animated: true, completion: nil)
                    
                    
                }else{
                    TSMessage.showNotification(in: self, title: "提示", subtitle: "非常抱歉，提交失败！请检查网络或者减少图片数量再次提交！谢谢使用\(appname)", image: nil, type: TSMessageNotificationType.error, duration: 2.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: true)
                }
                
            })
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        contentField.resignFirstResponder()
    }
    func InitViews() {
        //++++++++++++++++++++++++++++++++++++++++++
        /*
        contentField = FUITextField.init(frame: CGRect(x: 10, y: 74, width: screenW - 20, height: 100))
        contentField.layer.borderColor = UIColor.init(hexString: "f0f0f0", alpha: 1).cgColor
        contentField.layer.borderWidth = 1
        contentField.layer.cornerRadius = 3
        contentField.borderColor = barColor
        contentField.borderWidth = 2.0
        contentField.cornerRadius = 3
        contentField.textFieldColor = UIColor.white
        contentField.backgroundColor = UIColor.clear
        contentField.font = UIFont.systemFont(ofSize: 14)
        contentField.placeholder = "提交您的宝贵意见，帮助我们改善产品（150字内）"
        contentField.edgeInsets = UIEdgeInsetsMake(2.0, 8.0, 2.0, 8.0)
        */
        //++++++++++++++++++++++++++++++++++++++++++
        contentField = UITextView.init(frame: CGRect(x: 10, y: 74, width: screenW - 20, height: 100))
        
        contentField.backgroundColor = UIColor.init(hexString: "f2f2f2", alpha: 1)
        contentField.layer.borderColor = UIColor.init(hexString: "f0f0f0", alpha: 1.0).cgColor
//        UIColor(hexString: "4e92df", alpha: 1).cgColor

        contentField.layer.borderWidth = 1
        contentField.layer.cornerRadius = 3
        contentField.isScrollEnabled = true
        contentField.textColor = UIColor.darkGray
        contentField.isHidden = false
        contentField.delegate = self
        contentField.font = UIFont.systemFont(ofSize: 15)
        
        placeholderLabel = UILabel.init(frame: CGRect(x: contentField.frame.minX + 4, y: contentField.frame.minY + 7, width: screenW - 20 - 8, height: 20))
        placeholderLabel.text = "提交您的宝贵意见，帮助我们改善产品（150字内）"
        placeholderLabel.textColor = UIColor.init(hexString: "DBDBDB", alpha: 1.0)
        placeholderLabel.isEnabled = false
        placeholderLabel.backgroundColor = UIColor.clear
        placeholderLabel.font = UIFont.systemFont(ofSize: 15.0)
        
        //++++++++++++++++++++++++++++++++++++++++++
        
        self.view.addSubview(contentField)
        self.view.addSubview(placeholderLabel)
        
        photoCollectionView = UICollectionView.init(frame: CGRect(x: 10, y: contentField.frame.maxY + 10, width: screenW - 20, height: getAddPhotoCollectionHeight(photoArray)), collectionViewLayout: AddPhotoFlowLayout.init())
        photoCollectionView.backgroundColor = UIColor.clear
        photoCollectionView.register(PhotoCollectionViewCell.self, forCellWithReuseIdentifier: collectionIdentifier)
        photoCollectionView.scrollsToTop = true
        photoCollectionView.delegate = self
        photoCollectionView.dataSource = self
        self.view.addSubview(photoCollectionView)
        
    }
    
    //MARK: ui collection view delegate and data source
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return photoArray.count + 1
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: PhotoCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionIdentifier, for: indexPath) as! PhotoCollectionViewCell
        cell.backgroundColor = UIColor.white
        let count = (indexPath as NSIndexPath).row
        if count == photoArray.count {
            cell.photoImage.image = UIImage.init(named: "hnx")
        }else{
            let assest = photoArray.object(at: count)
            if (assest as AnyObject).isKind(of: UIImage.self) {
                cell.photoImage.image = assest as? UIImage
            }else{
                let ass = assest as! ALAsset
                cell.photoImage.image = UIImage.init(cgImage: ass.aspectRatioThumbnail().takeUnretainedValue())
            }
        }

        return cell;
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        contentField.resignFirstResponder()
        if (indexPath as NSIndexPath).row == photoArray.count {
            photoAdd()
        }else {
            print("选中第\(indexPath.row+1)张")
            //++++++++++++++++++++++++++++++++
            showBigImage(index: Int(indexPath.row))
        }
    }
    
    //MARK: - AJPhotoBrowserDelegate
    func photoBrowser(_ vc: AJPhotoBrowserViewController!, deleteWith index: Int) {
        //删除选中的照片
    }
    func photoBrowser(_ vc: AJPhotoBrowserViewController!, didDonePhotos photos: [Any]!) {
        //从相册点击确定
        self.photoArray.removeAllObjects()
        self.photoArray.addObjects(from: photos)
        
        self.photoCollectionView.reloadData()
        vc.dismiss(animated: true, completion: nil)
        
    }
    func showBigImage(index: Int) {
        var pphotos = [Any]()
        for i in 0..<photoArray.count {
            print("\(i) = \(photoArray.object(at: i))")
            pphotos.append(photoArray[i])
        }
        
        let photoBrowserVC = AJPhotoBrowserViewController.init(photos: pphotos, index: index)
        photoBrowserVC?.delegate = self
        self.present(photoBrowserVC!, animated: true, completion: nil)
    }
    
    func photoAdd() {

        let picker = AJPhotoPickerViewController.init()
        picker.maximumNumberOfSelection = 9
        picker.multipleSelection = true
        picker.assetsFilter = ALAssetsFilter.allPhotos()
        picker.showEmptyGroups = true
        picker.delegate = self
        self.present(picker, animated: true, completion: nil)
        
    }
    /**
     选中
     
     - parameter picker: <#picker description#>
     - parameter asset:  <#asset description#>
     */
    func photoPicker(_ picker: AJPhotoPickerViewController!, didSelect asset: ALAsset!) {
        
    }
    /**
     取消选中
     
     - parameter picker: <#picker description#>
     - parameter asset:  <#asset description#>
     */
    func photoPicker(_ picker: AJPhotoPickerViewController!, didDeselect asset: ALAsset!) {
        
    }
    /**
     完成
     
     - parameter picker: <#picker description#>
     - parameter assets: <#assets description#>
     */
    func photoPicker(_ picker: AJPhotoPickerViewController!, didSelectAssets assets: [AnyObject]!) {
        photoArray.removeAllObjects()
        photoArray.addObjects(from: assets)
        
        photoCollectionView.frame = CGRect(x: 10, y: contentField.frame.maxY + 10, width: screenW - 20, height: getAddPhotoCollectionHeight(photoArray))
        photoCollectionView.reloadData()
        
        picker.dismiss(animated: true, completion: nil)
    }
    /**
     取消选择
     
     - parameter picker: <#picker description#>
     */
    func photoPickerDidCancel(_ picker: AJPhotoPickerViewController!) {
        
        picker.dismiss(animated: true, completion: nil)
    }
    
    /**
     相机
     
     - parameter picker: <#picker description#>
     */
    func photoPickerTapCameraAction(_ picker: AJPhotoPickerViewController!) {
        if photoArray.count >= 9 {
            TSMessage.showNotification(in: picker, title: "提示", subtitle: "对不起，您选择的图片过多，现在只能支持最大9张图片", image: nil, type: TSMessageNotificationType.error, duration: 2.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: true)
        }else{
            picker.dismiss(animated: false, completion: nil);
            let pickCamer = UIImagePickerController()
            pickCamer.allowsEditing = false
            pickCamer.sourceType = UIImagePickerControllerSourceType.camera
            pickCamer.delegate = self
            pickCamer.cameraFlashMode = UIImagePickerControllerCameraFlashMode.auto
            self.present(pickCamer, animated: true, completion: nil)
        }
        
    }
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let dic: NSDictionary = info as NSDictionary
        let image = dic.object(forKey: UIImagePickerControllerOriginalImage)
        photoArray.add(image!)
        photoCollectionView.frame = CGRect(x: 10, y: contentField.frame.maxY + 10, width: screenW - 20, height: getAddPhotoCollectionHeight(photoArray))
        photoCollectionView.reloadData()
        
        picker.dismiss(animated: true, completion: nil)
    }
    
    /**
     超过最大
     
     - parameter picker: <#picker description#>
     */
    func photoPickerDidMaximum(_ picker: AJPhotoPickerViewController!) {
        TSMessage.showNotification(in: picker, title: "提示", subtitle: "对不起，您选择的图片过多，现在只能支持最大9张图片", image: nil, type: TSMessageNotificationType.error, duration: 2.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: true)
    }
    
    //MARK: - ui text view delegate 
    func textViewDidChange(_ textView: UITextView) {
        if textView.text.characters.count == 0 {
            placeholderLabel.text = "提交您的宝贵意见，帮助我们改善产品（150字内）"
        }else{
            placeholderLabel.text = ""
            contentField.layer.borderColor = UIColor.init(hexString: "4e92df", alpha: 1.0).cgColor
            contentField.layer.borderWidth = 2
            contentField.layer.cornerRadius = 4
        }
        
        let length = textView.text.characters.count
        if length > 200 {
            
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}




